# -*- coding: utf-8 -*-

import urllib
import hashlib
import os
import traceback
from termcolor import cprint


def getMD5Hash(textToHash=None):
    return hashlib.md5(textToHash).hexdigest()

def getMd5Path(stringToHash):
    s = getMD5Hash(stringToHash)
    s = '{0}/{1}/{2}/{3}'.format(s[0], s[1], s[2], s[3])
    return s

def getMd5FileName(stringToHash):
    s = getMD5Hash(stringToHash)
    s = '{0}/{1}/{2}/{3}/{4}'.format(s[0], s[1], s[2], s[3], s[4:])
    return s


def downloadNCT(url, download_path, prefix='', ext='mp3'):
    print 'call downloadNCT, prefix={0}, download_path={1}, url={2}, ext={3}'.format(prefix, download_path, url, ext)
    if download_path.endswith('/'): download_path = download_path[:-1]
    if prefix != '':
        if prefix.endswith('/'): prefix = prefix[:-1]
    if not url.endswith('mp3'): return -1, 'Error: only mp3 file accept'
    fileName = "{0}.{1}".format(getMd5FileName(url), ext)
    downloadPath = "{0}/{1}".format(download_path, fileName)
    success = False
    try:
        print 'download to {0}'.format(downloadPath)
        for i in (0, 4):
            if not os.path.isfile(downloadPath):
                path = os.path.dirname(downloadPath)
                if not os.path.exists(path): os.system("mkdir -p -m 0777 {0}".format(path))
                local, res = urllib.urlretrieve(url, downloadPath)
                if res == None: continue
                responseSize = long(res.get('Content-Length'))
                downloadedSize = os.path.getsize(local)
                if "text/html" in res.get('Content-Type') and os.path.isfile(local): os.unlink(local); continue
                if downloadedSize < responseSize and os.path.isfile(local): os.unlink(local); continue
                success = True
            else:
                success = True
            if success: break
    except:
        traceback.print_exc()
    if success: return os.path.getsize(downloadPath), "{0}/{1}".format(prefix, fileName)
    return -1, 'Error: download failed'
